package addressbook

import (
	"errors"
	"public_security/databases"
	"public_security/models"
)

func Create(req *models.AddressBook) error {
	if err := databases.DbDefault.Model(&models.AddressBook{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func Update(req *models.AddressBook) error {
	if err := databases.DbDefault.Model(&models.AddressBook{}).Where("id=?", req.Id).Updates(map[string]interface{}{
		"name":                 req.Name,
		"phone":                req.Phone,
		"address_book_type_id": req.AddressBookTypeId,
		"level":                req.Level,
	}).Error; err != nil {
		return err
	}
	return nil
}

func Remove(req *models.AddressBook) error {
	if err := databases.DbDefault.Model(&models.AddressBook{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func Query(req *models.AddressBook) []*models.AddressBook {
	arts := make([]*models.AddressBook, 0)
	databases.DbDefault.Model(req).Preload("AddressBookType").Find(&arts)
	return arts
}

func CreateType(req *models.AddressBookType) error {
	if err := databases.DbDefault.Model(&models.AddressBookType{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func UpdateType(req *models.AddressBookType) error {
	if err := databases.DbDefault.Model(&models.AddressBookType{}).Where("id=?", req.Id).Updates(map[string]interface{}{"name": req.Name}).Error; err != nil {
		return err
	}
	return nil
}

func RemoveType(req *models.AddressBookType) error {
	var count int
	databases.DbDefault.Model(&models.AddressBook{}).Select("count(id)").Where("address_book_type_id=?", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("正在使用的中队分类，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.AddressBookType{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func QueryType(req *models.AddressBookType) []*models.AddressBookType {
	arts := make([]*models.AddressBookType, 0)
	databases.DbDefault.Model(req).Find(&arts)
	return arts
}
